//app.js
App({
  globalData: {
    // BASE_URL: "https://localhost:5443/api",
    BASE_URL: "https://chenborui.xyz:5443/api",
    STORAGE_NAME: 'token',
    TOKEN: null,
    isLogin: false,
    userInfo: {
    }
  },
  onLaunch: function() {
    this.judgeLoginStatus(() => {})
  },
  //判断是否登录
  judgeLoginStatus(success) {
    let that = this
    wx.getStorage({
      key: this.globalData.STORAGE_NAME,
      success(res) {
        that.globalData.TOKEN = 'Bearer ' + res.data    //设置token
        that.globalData.isLogin = true
        that.requestUserInfo(() => {
          success()
        })
      }
    })
  },

  requestUserInfo(success) {
    wx.showLoading({
      title: '加载中',
    });
    // 提交数据
    let that = this
    wx.request({
      url: that.globalData.BASE_URL + "/getInfo",
      data: {
      },
      header: {
        'content-type': 'application/json',
        'Authorization': this.globalData.TOKEN
      },
      success(res) {
        res = that.responseInterceptor(res)
        if (res === undefined) return;
        that.globalData.userInfo = res.data
        wx.hideLoading();
        success()
      }
    })
  },
  logout() {
    wx.request({
      url: this.globalData.BASE_URL + "/logout",
      method: 'post',
      header: {
        'content-type': 'application/json',
        'Authorization': this.globalData.TOKEN
      },
      success(res) {}
    })
    this.clearInfo()
  },
  clearInfo(){
    this.globalData.isLogin = false
    this.globalData.TOKEN = ''
    this.globalData.userInfo = {}
    wx.clearStorageSync()
  },

  //响应拦截器
  responseInterceptor(res) {
    if (res.data.code === 401) {
      wx.hideLoading();
      let that = this
      wx.showModal({
        title: '系统提示',
        content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
        confirmText: '前往登录',
        success(res) {
          if (res.confirm) {
            that.clearInfo()
            wx.showLoading({
              title: '跳转中...',
            });
            wx.navigateTo({
              url: '/pages/login/index/index',
              complete: () => {
                wx.hideLoading();
              }
            })
          }
        }
      })
    } else if (res.data.code !== 200) {
      wx.hideLoading();
      wx.showToast({
        title: res.data.msg,
        icon: 'none',
        duration: 1500
      });
    } else {
      return res.data
    }
  }
})